import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import pl.edu.szlif.mosm.commonlib.http.GenericHTTPConnection;

public class J2MEGenericHttpConnectionImpl extends GenericHTTPConnection {

	private HttpConnection connection = null;
	private boolean inSetup = true;

	public J2MEGenericHttpConnectionImpl() {
	}

	private J2MEGenericHttpConnectionImpl(String url, int method) throws IOException {
		if (url == null) {
			throw new NullPointerException("A url null parameter");
		}
		if (method != GenericHTTPConnection.GET && method != GenericHTTPConnection.POST) {
			throw new NullPointerException("Invalid method value");
		}
		connection = (HttpConnection) Connector.open(url);
		connection.setRequestMethod(method == GenericHTTPConnection.GET ? HttpConnection.GET : HttpConnection.POST);
	}

	public int execute() throws IOException {
		inSetup = false;
		return connection.getResponseCode();
	}

	public InputStream getInputStream() throws IOException {
		if (connection == null) {
			throw new IOException("Attempt to read from a unconnected instance");
		}
		if (inSetup) {
			throw new IOException("Cannot be invoked in setup mode");
		}
		return connection.openInputStream();
	}

	public OutputStream getOutputStream() throws IOException {
		if (connection == null) {
			throw new IOException("Attempt to write to a unconnected instance");
		}
		if (!inSetup) {
			throw new IOException("Cannot be invoked after setup is completed");
		}
		return connection.openOutputStream();
	}

	public String getRequestHeader(String key) throws IOException {
		if (connection == null) {
			throw new IOException("Attempt to read from a unconnected instance");
		}
		return connection.getRequestProperty(key);
	}

	public String getResponseHeader(String key) throws IOException {
		if (connection == null) {
			throw new IOException("Attempt to read from a unconnected instance");
		}
		if (inSetup) {
			throw new IOException("Cannot be invoked in setup mode");
		}
		return connection.getHeaderField(key);
	}

	public GenericHTTPConnection open(String url, int method) throws IOException {
		return new J2MEGenericHttpConnectionImpl(url, method);
	}

	public void setRequestHeader(String key, String value) throws IOException {
		if (connection == null) {
			throw new IOException("Attempt to read from a unconnected instance");
		}
		if (!inSetup) {
			throw new IOException("Cannot be invoked after setup is completed");
		}
		connection.setRequestProperty(key, value);
	}

}
